<?php
class Voucher extends BZ_Controller
{
    public function _init()
    {
        $this->load->library(array('encrypt', 'sms/sms', 'alidayu/alidayusms'));
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('voucher_model', 'voucher');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('ym_sms_error_model', 'ym_sms_error');
    }

    public function index()
    {
        $this->load->view('login/voucher/index');
    }
    
    public function success()
    {
        $user_name = $this->input->get('user_name');
        $password  = $this->input->get('password');
        $amount    = $this->input->get('amount');
        
        $data['user_name'] = $user_name;
        $data['password'] = $password;
        $data['amount'] = $amount;
        
        $this->load->view('login/voucher/success', $data);
    }
    
    //使用代金券
    public function getVoucher()
    {
        $code   = $this->input->post('code');
        $phone  = $this->input->post('phone');
        $verify_code = $this->input->post('verify');
        
        $res = $this->voucher->getVoucherByCode($code);
        if ($res->num_rows() <= 0) {
            $this->jsonMessage('串码错误。');
        }
        $vou_info = $res->row_array();
        if (2 == $vou_info['status']) {
            $this->jsonMessage('该代金券已使用。');
        }
        
        //验证验证码
        if (empty($verify_code)) {
             $this->jsonMessage('验证码不能为空');
        }
        $postData['mobile_phone'] = $phone;
        $postData['verify'] = $verify_code;
        $verify = $this->getpwd_phone->validateName($postData, true);
        if ($verify->num_rows() <= 0) { //验证码无效
            $this->jsonMessage('无效的验证码');
        }
        
        //验证手机号是否已注册及用户类型
        //$r1 = $this->user->validateName($phone);
        $r2 = $this->user->validateMobilePhone($phone);
        if ($r2->num_rows() > 0) {
            $user_list = $r2->result_array();
            if ((($vou_info['user_type']&64)==64) || (($vou_info['user_type']&256)==256) || (($vou_info['user_type']&1024)==1024) || (($vou_info['user_type']&4096)==4096)) {
                foreach ($user_list as $one_user) {
                    if ((($one_user['user_type']&64)==64) || (($one_user['user_type']&256)==256) || (($one_user['user_type']&1024)==1024) || (($one_user['user_type']&4096)==4096)) {
                        $this->jsonMessage('手机号已绑定分销类型账户。');
                    }
                }
            } elseif(($vou_info['user_type']&16384)==16384) {//消费者
                foreach ($user_list as $one_user) {
                    if ((($one_user['user_type']&1)!=1) && (($one_user['user_type']&2)!=2)) {//非供应商
                        $this->jsonMessage('手机号已绑定消费类型账户。');
                    }
                }
            }
        }
         
        $vou_info['phone'] = $phone;
        $ret = $this->addUser($vou_info);
        if (!$ret) {
            $this->jsonMessage('生成用户失败。');
        }
        
        //$this->sendToSms($phone, '您于'.date('Y-m-d H:i:s').'成功激活串码，账户名为:'.$ret['user_name'].'，密码为：'.$ret['password'].'，代金券金额'.$vou_info['amount'].'。详情请登录官网。');
        $alidayusms = $this->alidayusms->smsNumSend($phone, json_encode(array('date'=>date('Y-m-d H:i:s'), 'user_name'=>$ret['user_name'], 'password'=>$ret['password'], 'amount'=>$vou_info['amount'])), 'SMS_36330066');
        if (isset($alidayusms['success']) && $alidayusms['success'] == 'false') {
            $this->ym_sms_error->insertYmSmsError($phone, json_encode(array('date'=>date('Y-m-d H:i:s'), 'user_name'=>$ret['user_name'], 'password'=>$ret['password'], 'amount'=>$vou_info['amount'])), json_encode($alidayusms), 4);
        }
        $url = site_url('login/voucher/success').'?user_name='.$ret['user_name'].'&password='.$ret['password'].'&amount='.$vou_info['amount'];
        echo json_encode(array(
            'status'   => true,
            'messages' => $url
        ));exit;
    }
    
    //生成用户
    private function addUser($vou_info)
    {
        $letters = $vou_info['prefix'];
        $digi_count = $vou_info['digi_count'];
        
        //生成最大数字
        $max = 0;
        for ($i=1; $i<=$digi_count; $i++) {
            $max = $max*10+9;
        }
        
        //生成并保存用户
        for ($i=0; $i<$max+1; $i++) {
            $num = mt_rand(0, $max);
            $zero_count = $digi_count - strlen($num);
            while ($zero_count>0) {
                $num = '0'.$num;
                $zero_count--;
            }
            $user_name = $letters.'_'.$num;
            $pwd = mt_rand(10000000,99999999);
            
            $postData = array(
                 'user_name' => $user_name,
                 'alias_name'=> $user_name,
            );
            $find = $this->user->findByUserName($postData);
            
            if ($find->num_rows() <= 0) {
                $this->db->trans_start();
                $data_user = array(
                    'username'     => $user_name,
                    'mobile_phone' => $vou_info['phone'],
                    'user_type'    => $vou_info['user_type'],
                    'password'     => $pwd,
                );
                $uid = $this->user->insertUser($data_user, $vou_info['parent_id']);
                
                $amount_carry = 0;
                $amount_bonus = 0;
                if (1 == $vou_info['type']) {//可提现
                    $amount_carry = $vou_info['amount'];
                } elseif (2 == $vou_info['type']) {//游币 
                    $amount_bonus = intval($vou_info['amount']);
                }
                $this->user_account->insertVoucherUserAccount(array('amount_carry'=>$amount_carry,'over_beizhu'=>$vou_info['over_beizhu'],'amount_bonus'=>$amount_bonus),$uid);

                $data_voucher = array(
                    'status'    => 2,//已派发
                    'uid'       => $uid,
                    'user_name' => $user_name,
                    'password'  => base64_encode($pwd),
                    'get_way'   => 1,//创建账号
                );
                $this->voucher->updateVoucher($vou_info['id'], $data_voucher);
                
                $this->db->trans_complete();

                if ($this->db->trans_status() === TRUE) {
                    return array('user_name'=>$user_name,'password'=>$pwd);
                    break;
                }
            }
        }
        return FALSE;
    }
    
    /**
     * 生成并发送验证码。
     */
    public function checkPhone()
    {
        $phone = $this->input->post('phone');
        if (!valid_mobile($phone)) {
            $this->jsonMessage('手机号码格式有误');
        }

        $code = mt_rand(1000, 9999);
        $result = $this->getpwd_phone->validateName(array('mobile_phone'=>$phone));
        if ($result->num_rows() > 0) {
            $status = $this->getpwd_phone->updateGetpwdPhone(array('mobile_phone'=>$phone, 'code'=>$code));
        } else {
            $status = $this->getpwd_phone->insertGetpwdPhone(array('mobile_phone'=>$phone, 'code'=>$code));
        }
        //$this->sendToSms($phone, '您于'.date('Y-m-d H:i:s').'使用代金券获取着想账号，验证码为:'.$code.'，有效期为10分钟。');
        $alidayusms = $this->alidayusms->smsNumSend($phone, json_encode(array('date'=>date('Y-m-d H:i:s'), 'code'=>$code)), 'SMS_36235040');
        if (isset($alidayusms['success']) && $alidayusms['success'] == 'false') {
            $this->ym_sms_error->insertYmSmsError($phone, json_encode(array('date'=>date('Y-m-d H:i:s'), 'code'=>$code)), json_encode($alidayusms), 4);
        }
        if ($status) {
            $this->jsonMessage('');
        } else {
            $this->jsonMessage('网络繁忙，请稍后重试');
        }
    }
    
    //用户中心—用代金券给用户充值接口
    public function recharge()
    {
        //获取入口参数
        $uid = $this->input->post('uid');
        $code = $this->input->post('code');
         
        //验证UID，获取用户信息
        if (empty($uid)) {
             $this->jsonMessage('用户ID不能为空');
        }
        $result = $this->user->findByUid($uid);
        if ($result->num_rows()<=0) {
             $this->jsonMessage('该用户ID不存在');
        }
        $user_info = $result->row_array();
         
        //验证串码，获取代金券信息
        if (empty($code)) {
             $this->jsonMessage('串码不能为空');
        }
        $res = $this->voucher->getVoucherByCode($code);
        if ($res->num_rows()<=0) {
            $this->jsonMessage('串码错误。');
        }
        $vou_info = $res->row_array();
        if (2 == $vou_info['status']) {
            $this->jsonMessage('该代金券已使用。');
        }
        
        $this->db->trans_start();
        
        $this->user_account->updateVoucherUserAccount($user_info['uid'],$vou_info['type'],$vou_info['amount']);//更新用户账户信息
        
        $data_voucher = array(
            'status'    => 2,//已派发
            'uid'       => $user_info['uid'],
            'user_name' => $user_info['user_name'],
            'get_way'   => 2,//充值
        );
        $this->voucher->updateVoucher($vou_info['id'], $data_voucher);
        
        $data_log = array(
            'uid'=>$user_info['uid'],
            'amount'=>$vou_info['amount'],
            'type'=>($vou_info['type']==1)?16:32768,//虚拟充值：游币
            'account_type'=>($vou_info['type']==1)?1:4,//可提现：游币
        );
        $this->account_log->insertAccountLog($data_log);
        
        $this->db->trans_complete();

        if ($this->db->trans_status() === TRUE) {
            $this->jsonMessage('');//充值成功
        } else {
            $this->jsonMessage('充值失败！');
        }
    }
}